'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'
import RequireAuth from '@/components/auth/RequireAuth'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { toast } from 'react-hot-toast'
import { Button } from '@/components/ui/button'
import CountdownTimer from '@/components/orders/CountdownTimer'
import ReviewDialog from '@/components/orders/ReviewDialog'

interface Order {
  id: number
  spot_id: number
  quantity: number
  total_price: number
  status: string
  visit_date: string
  created_at: string
  expires_at: string
  spot: {
    name: string
    images: string
  }
  contact_name: string
  contact_phone: string
  rating?: number
  is_anonymous: boolean
  comment: string
  commented_at: string
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(true)
  const [showReview, setShowReview] = useState(false)
  const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null)

  const fetchOrders = async () => {
    try {
      setLoading(true)
      const res = await api.get('/api/orders')
      setOrders(res.data)
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '获取订单列表失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchOrders()
    
    // 每30秒刷新一次订单列表
    const intervalId = setInterval(fetchOrders, 30000)
    
    return () => clearInterval(intervalId)
  }, [])

  const handlePay = async (orderId: number) => {
    try {
      await api.post(`/api/orders/${orderId}/pay`)
      toast.success('支付成功')
      fetchOrders()  // 刷新订单列表
    } catch (error) {
      toast.error('支付失败')
    }
  }

  const handleCancel = async (orderId: number) => {
    try {
      await api.post(`/api/orders/${orderId}/cancel`)
      toast.success('订单已取消')
      fetchOrders()  // 刷新订单列表
    } catch (error) {
      toast.error('取消订单失败')
    }
  }

  const handleTimeout = async (orderId: number) => {
    try {
      await api.post(`/api/orders/${orderId}/cancel`)
      fetchOrders()  // 刷新订单列表
    } catch (error) {
      console.error('Failed to cancel timed out order:', error)
    }
  }

  const handleReview = (orderId: number) => {
    setSelectedOrderId(orderId)
    setShowReview(true)
  }

  const handleDelete = async (orderId: number) => {
    if (!confirm('确定要删除此订单吗？')) {
      return
    }
    
    try {
      await api.delete(`/api/orders/${orderId}`)
      toast.success('订单已删除')
      fetchOrders()  // 刷新订单列表
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '删除订单失败')
    }
  }

  if (loading) {
    return <div>加载中...</div>
  }

  const getStatusText = (status: string, rating?: number) => {
    if (status === 'paid' && rating) {
      return '已评价'
    }
    switch (status) {
      case 'pending':
        return '待支付'
      case 'paid':
        return '已支付'
      case 'completed':
        return '已完成'
      case 'cancelled':
        return '已取消'
      default:
        return status
    }
  }

  const getStatusColor = (status: string, rating?: number) => {
    if (status === 'paid' && rating) {
      return 'bg-purple-100 text-purple-800'
    }
    switch (status) {
      case 'pending':
        return 'bg-yellow-100 text-yellow-800'
      case 'paid':
        return 'bg-green-100 text-green-800'
      case 'completed':
        return 'bg-blue-100 text-blue-800'
      case 'cancelled':
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  return (
    <RequireAuth>
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          <h1 className="text-2xl font-bold mb-6">我的订单</h1>
          <div className="space-y-6">
            {orders.map((order) => (
              <div key={order.id} className="bg-white shadow rounded-lg p-6">
                <div className="flex items-center justify-between">
                  <h2 className="text-lg font-medium text-gray-900">
                    {order.spot?.name || '未知景点'}
                  </h2>
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(order.status, order.rating)}`}>
                    {getStatusText(order.status, order.rating)}
                  </span>
                </div>
                <div className="mt-4 space-y-2 text-sm text-gray-500">
                  <div>数量：{order.quantity} 张</div>
                  <div>总价：¥{order.total_price}</div>
                  <div>游玩日期：{format(new Date(order.visit_date), 'yyyy年MM月dd日', { locale: zhCN })}</div>
                  <div>联系人：{order.contact_name}</div>
                  <div>联系电话：{order.contact_phone}</div>
                  <div>下单时间：{format(new Date(order.created_at), 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })}</div>
                </div>
                {order.status === 'pending' && (
                  <div className="mt-2">
                    <CountdownTimer 
                      createdAt={order.created_at}
                      expiresAt={order.expires_at}
                      orderId={order.id}
                      onTimeout={() => handleTimeout(order.id)}
                    />
                  </div>
                )}
                {order.status === 'pending' && (
                  <div className="mt-4 flex justify-end space-x-4">
                    <Button
                      variant="outline"
                      onClick={() => handleCancel(order.id)}
                    >
                      取消订单
                    </Button>
                    <Button
                      onClick={() => handlePay(order.id)}
                    >
                      立即支付
                    </Button>
                  </div>
                )}
                {(order.status === 'cancelled' || order.status === 'paid') && (
                  <div className="mt-4 flex justify-end space-x-4">
                    <Button
                      variant="destructive"
                      onClick={() => handleDelete(order.id)}
                    >
                      删除订单
                    </Button>
                    {order.status === 'paid' && !order.rating && (
                      <Button onClick={() => handleReview(order.id)}>
                        评价订单
                      </Button>
                    )}
                  </div>
                )}
                {order.rating && (
                  <div className="mt-4 border-t pt-4">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-2">
                          <span className="text-sm text-gray-500">评分：</span>
                          {[1, 2, 3, 4, 5].map((value) => (
                            <svg
                              key={value}
                              className={`h-4 w-4 ${
                                value <= order.rating ? 'text-yellow-400' : 'text-gray-200'
                              }`}
                              fill="currentColor"
                              viewBox="0 0 20 20"
                            >
                              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                            </svg>
                          ))}
                        </div>
                        <span className="text-sm text-gray-500">
                          {order.is_anonymous ? '匿名评价' : '实名评价'}
                        </span>
                      </div>
                      <p className="text-gray-600">{order.comment}</p>
                      <div className="flex justify-between items-center">
                        <span className="text-sm text-gray-500">
                          {format(new Date(order.commented_at), 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })}
                        </span>
                        {order.status === 'paid' && (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleReview(order.id)}
                          >
                            修改评价
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}

            {orders.length === 0 && (
              <div className="text-center text-gray-500 py-8">
                暂无订单记录
              </div>
            )}
          </div>
        </div>
      </div>

      {selectedOrderId && (
        <ReviewDialog
          orderId={selectedOrderId}
          open={showReview}
          onOpenChange={(open) => {
            setShowReview(open)
            if (!open) setSelectedOrderId(null)
          }}
          onSuccess={fetchOrders}
        />
      )}
    </RequireAuth>
  )
} 